import React, { useState, useEffect } from 'react';
import { View, Image, ScrollView, StyleSheet, Text, Modal, TouchableOpacity, TextInput } from 'react-native';
import ProfileEditor from '@/components/features/device/ProfileEditor';
import { WhiteSpace } from '@ant-design/react-native';
import FamilyMemberCard from '@/components/features/device/FamilyMemberCard';
import QRCode from 'react-native-qrcode-svg';
import { createFamily, generateInviteCode, joinFamily, getFamilyMembers } from '../api/family';
import { registerUser, loginUser, logoutUser, refreshToken, getUserProfile } from '../api/auth';
import { Stack, useFocusEffect } from 'expo-router';
import { LinearGradient } from 'expo-linear-gradient';

type FamilyMember = {
    id: number;
    username: string;
    family_name: string;
    role: string; // 例如 'owner', 'member'
    joined_at: string; // 加入时间
};
export default function DevicePage() {
    const [familyName, setFamilyName] = useState<string | null>(null);
    const [inviteCode, setInviteCode] = useState('');
    const [members, setMembers] = useState<FamilyMember[]>([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [me, setMe] = useState('');

    useEffect(() => {
        fetchFamilyMembers(); // 获取家庭成员列表
        fetchMe(); // 获取自己的信息
    }, []);

    const fetchFamilyMembers = async () => {
        try {
            const response = await getFamilyMembers();
            setMembers(response.data);
            setFamilyName(response.data[0]?.family_name || '')
            console.log('获取家庭成员成功:', response.data);
        } catch (error) {
            console.error('获取家庭成员失败:', error);
        }
    };

    const fetchMe = async () => {
        try {
            const response = await getUserProfile();
            setMe(response.data.username);
            console.log('获取用户信息成功:', response.data);
        } catch (error) {
            console.error('获取用户信息失败:', error);
        }
    };

    // 触发ActionSheet，弹出二维码
    const handleAddMember = async () => {
        try {
            const response = await generateInviteCode();
            // setInviteCode(res.data.data.code);
            setInviteCode(response.data.code);
            console.log('Generate invite code response:', response.data);
            setModalVisible(true);
        } catch (e) {
            alert('生成邀请码失败');
        }
    };

    return (
        <View style={{ flex: 1, backgroundColor: '#fff' }}>
            {/* 背景图片 */}
            <Image
                source={require('../assets/images/wheat.jpg')}
                style={styles.bgImage}
                resizeMode="cover"
            />
            {/* 图片下方渐变遮罩 */}
            <LinearGradient
                colors={['transparent', '#fff']} // 从透明到白色，可根据背景色调整
                style={styles.gradient}
            />
            <ScrollView style={{ flex: 1, backgroundColor: 'transparent' }}>
                <View style={{ alignItems: 'center', marginTop: 80, marginBottom: 200 }}>
                    <View style={{ width: '100%', maxWidth: 400, alignItems: 'center' }}>
                        <Text style={[styles.title, { alignSelf: 'flex-start', marginLeft: 30 }]}>
                            {familyName}
                        </Text>
                        <Text style={[styles.desc, { alignSelf: 'flex-start', marginLeft: 30 }]}>
                            {members.length}个成员
                        </Text>
                        <WhiteSpace size="lg" />
                        <WhiteSpace size="lg" />
                        <Text style={[styles.desc, { alignSelf: 'flex-start', marginLeft: 30 }]}>
                            家庭名称
                        </Text>
                        <WhiteSpace size="lg" />
                        <TextInput
                            style={{
                                width: 330,
                                height: 44,
                                borderColor: '#ccc',
                                borderWidth: 1,
                                borderRadius: 8,
                                paddingLeft: 12,
                                marginLeft: 30,
                                marginRight: 30,
                                backgroundColor: '#f9f9f9'
                            }}
                            value={familyName || ''}
                            onChangeText={setFamilyName}
                            placeholder="请输入家庭名称"
                            placeholderTextColor="#aaa"
                        />
                        <WhiteSpace size="lg" />
                        <WhiteSpace size="lg" />
                        <WhiteSpace size="lg" />
                        <Text style={[styles.desc, { alignSelf: 'flex-start', marginLeft: 30 }]}>
                            家庭成员
                        </Text>
                        <WhiteSpace size="lg" />
                        <View style={{ width: 330, borderRadius: 20, overflow: 'hidden', borderWidth: 1, borderColor: '#ddd' }}>
                            <WhiteSpace size='sm' />
                            {members.map((member, idx) => (
                                <FamilyMemberCard
                                    key={idx}
                                    username={member.username}
                                    owner={member.role === "管理员"}
                                    me={member.username === me}
                                />
                            ))}
                            <FamilyMemberCard
                                addCard={true}
                                onEditPress={handleAddMember}
                            />
                            <WhiteSpace size="sm" />
                        </View>
                    </View>
                </View>
            </ScrollView>

            {/* ActionSheet 弹窗，显示二维码 */}
            <Modal
                visible={modalVisible}
                animationType="slide"
                transparent
                onRequestClose={() => setModalVisible(false)}
            >
                <View style={styles.modalContainer}>
                    <View style={styles.sheet}>
                        <Text style={styles.sheetTitle}>邀请二维码</Text>
                        <QRCode
                            value={inviteCode}
                            size={250}
                        />
                        <TouchableOpacity onPress={() => setModalVisible(false)} style={styles.closeBtn}>
                            <Text style={{ color: '#3366cc', fontSize: 16 }}>关闭</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </Modal>
        </View>
    );
}

const styles = StyleSheet.create({
    title: {
        marginLeft: 0,
        color: '#000',
        fontSize: 28,
        fontWeight: 'bold',
    },
    desc: {
        color: '#888',
        fontSize: 18,
        marginTop: 4,
    },
    modalContainer: {
        flex: 1,
        justifyContent: 'flex-end',
        backgroundColor: 'rgba(0,0,0,0)',
    },
    sheet: {
        backgroundColor: '#fff',
        borderTopLeftRadius: 24,
        borderTopRightRadius: 24,
        borderWidth: 1,
        borderColor: '#ddd',
        padding: 24,
        alignItems: 'center',
    },
    sheetTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 16,
    },
    closeBtn: {
        marginTop: 24,
    },
    bgImage: {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: 300,
        zIndex: -1, // 保证图片在内容下方
    },
    gradient: {
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        top: 250, // 从图片底部开始渐变
        height: 50, // 渐变高度，可调整
        zIndex: -1,
    },
});
